<?php
session_start();

// 如果已经登录，直接跳转到首页
if (isset($_SESSION['user'])) {
    header('Location: index.php');
    exit;
}

// 处理登录请求
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once 'includes/functions.php';
    
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (empty($username) || empty($password)) {
        $error = '请输入用户名和密码';
    } else {
        $user = authenticate($username, $password);
        if ($user) {
            $_SESSION['user'] = $user;
            header('Location: index.php');
            exit;
        } else {
            $error = '用户名或密码错误';
        }
    }
}

$pageTitle = "登录";
include 'includes/header.php';
?>

<div class="login-container">
    <div class="login-box">
        <div class="logo">
            <i class="fas fa-blog"></i>
            <span>个人博客</span>
        </div>
        <h2>欢迎回来</h2>
        
        <?php if ($error): ?>
            <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <form method="POST" action="">
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" name="username" placeholder="请输入用户名" required value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>">
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" name="password" placeholder="请输入密码" required>
            </div>
            <button type="submit" class="btn">登录</button>
        </form>
        
        <div class="login-footer">
            <p>默认账号：admin / 123456</p>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
